const Client = require("ssh2").Client;

class Core {}
Core.conn = conn = new Client();
let isConnect = false;
let config = null;
//开启连接
Core.connect = function(params) {
  return new Promise((resolve, reject) => {
    conn
      .on("ready", function() {
        isConnect = true;
        config = params;
        resolve();
      })
      .connect({
        host: params.host,
        port: params.port || 22,
        username: params.username,
        password: params.password
      });
  });
};

//检查erlang环境
function checkErlangEnv() {
  return new Promise((resolve, reject) => {
    conn.exec("erl", (err, stream) => {
      if (err) reject(err);
      streamWork(resolve, reject, stream);
    });
  });
}
Core.checkErlangEnv = checkErlangEnv;

function startServer() {
  return new Promise((resolve, reject) => {
    if (config.remoteWorkDir) reject({ code: -1, msg: "请配置远程项目地址" });
    conn.exec(
      `cd ${config.remoteWorkDir}/pi/back/boot/ && sh ${config.startScript|| 'start.sh'}`,
      (error, stream) => {
        streamWork(resolve, reject, stream);
      }
    );
  });
}
Core.startServer = startServer
/**
 * 获取erlang进程pid
 * @param {Function} cb 结果回调
 */
function getPid() {
  return new Promise((resolve, reject) => {
    conn.exec("ps -aux|grep beam", (error, stream) => {
      streamWork(resolve, reject, stream);
    });
  });
}
Core.getPid = getPid;
/**
 * 停止进程
 * @param  cb 执行结果回调
 */
function stopProcess(pid) {
  return new Promise((resolve, reject) => {
    conn.exec(`kill -9 ${pid}`, (err, stream) => {
      streamWork(resolve, reject, stream);
    });
  });
}
Core.stopProcess = stopProcess

function streamWork(resolve, reject, stream) {
  stream
    .on("close", function(code, signal) {resolve()})
    .on("data", function(data) {
      resolve(data + "");
    })
    .stderr.on("data", function(data) {
      reject(data + "");
    });
}
Core.streamWork = streamWork
module.exports = Core;
